class Company < ApplicationRecord
  
  has_many :contacts, class_name: "Contact", foreign_key: "companies_id", dependent: :destroy
  has_many :followup_records, class_name: "FollowupRecord", foreign_key: "companies_id", dependent: :destroy
  belongs_to :employee, class_name: "Employee", foreign_key: "followup_employee_code", primary_key: "emp_code"

  validates :name, presence: true, length: { maximum: 50 } # uniqueness: { case_sensitive: false }
  validates :phone_no, length: { maximum: 20 }
  validates :postal_code, length: { maximum: 6 }
  validates :address, length: { maximum: 100 }
  validates :followup_employee_code, length: { maximum: 10 }

  default_scope { where("is_delete = 0") }

  # 查询没有跟进任务的公司
  def query_has_no_followup_records_companies
    Company.find_by_sql("select c.* from companies c where not exists (select 1 from followup_records f where f.companies_id = c.id and f.is_delete = 0) and c.is_delete = 0")
  end

end
